local blaze = require "blaze"
local game = require "club.threecard.sudoku"

local PlayerState = require "club.threecard.sudoku.ui.settlement.PlayerState"

local log = blaze.logging.get("SettlementUI")

local M = game.ui.activity()

M.store_watchers = {
    settlement = {
        ["$"] = function(self, store, state, args, init)
            self:update(state, args, init)
        end,
        ["结算"] = function(self, store, state, args)
            self:update(state, args)
            if args.winner == game.kbe.player().user_id then
                self.win_obj:SetActive(true)
                self.lose_obj:SetActive(false)
                game.audio.post("win")
            else
                self.win_obj:SetActive(false)
                self.lose_obj:SetActive(true)
                game.audio.post("lose")
            end
        end
    }
}

function M:ctor()
    self.res = "club.threecard.sudoku/ui/settlement.b:SettlementUI"
    self.player_states = {
        PlayerState.new(),
        PlayerState.new()
    }
    self.player_state = PlayerState.new()
end

function M:on_load()
    self:super("on_load")
    for _, player_state in ipairs(self.player_states) do
        player_state:load()
    end
    self.player_state:load()
end

function M:on_injected(bind)
    bind("button.click", self.continue_btn, self.on_continue)
    bind("button.click", self.back_btn, self.on_back)
    bind("shortcut.escape", self.back_btn.gameObject, self.on_back)
    bind("gameobject.element", self.single_root:Find("player").gameObject, self.player_state)
    for i, player_state in ipairs(self.player_states) do
        bind("gameobject.element", self.players_root:Find("player" .. tostring(i)).gameObject, self.player_states[i])
    end
end

function M:update(state, args, init)
    local player_count = #state.players
    if player_count == 1 then
        self.single_root.gameObject:SetActive(true)
        self.players_root.gameObject:SetActive(false)
        self.player_state:update(state.players[1], state.statistics[1])
    elseif player_count == 2 then
        self.single_root.gameObject:SetActive(false)
        self.players_root.gameObject:SetActive(true)
        for i, player in ipairs(state.players) do
            self.player_states[i]:update(player, state.statistics[i])
        end
    elseif not init then
        self.single_root.gameObject:SetActive(false)
        self.players_root.gameObject:SetActive(false)
        log.error("不支持的结算人数：" .. blaze.dump(state.players))
    end
end

function M:on_back()
    game.audio.post("click")
    game.store.settlement.backward()
end

function M:on_continue()
    game.audio.post("click")
    game.store.settlement.continue()
end

return M